<template>
    <div :class="$style['event-container-fixed']" v-if="show"
        :style="{ transform: `translate(calc(-50% + ${position.x}px), calc(-50% + ${position.y}px))` }" ref="dragRef">
        <div :class="$style['event-tooltip']" @mousedown="startDrag">
            <div :class="$style['event-icon-wrapper']">
                <el-image :src="require('@/assets/event-fixed-lb.png')" />
                <span>{{ info.event_name }}</span>
            </div>
            <el-icon :size="12" color="#A6B8C6" @click="show = false">
                <Close />
            </el-icon>
        </div>
        <el-tabs v-model="activeName" :class="$style['event-content-container']" @tab-change="switchTab">
            <el-tab-pane label="事件详情" name="1" :class="$style['tab-pane-wrapper']">
                <el-form>
                    <el-form-item label="设备名称:">{{ info.device_name }}</el-form-item>
                    <el-form-item label="所在区域:">{{ info.area_name }}</el-form-item>
                    <el-form-item label="设备类型:">{{ info.node_name }}</el-form-item>
                    <el-form-item label="事件分类:">{{ info.event_type_name }}</el-form-item>
                    <el-form-item label="事件等级:">{{ info.event_level_name }}</el-form-item>
                    <el-form-item label="安装位置:">{{ info.dvc_installation }}</el-form-item>
                    <el-form-item label="发生时间:">{{ info.event_time }}</el-form-item>
                    <el-form-item label="事件备注:">{{ info.event_desc }}</el-form-item>
                    <el-form-item label="处理意见:" style="margin-bottom: 5px;">
                        <el-input type="textarea" disabled v-model="info.handle_remark" rows="2" style="width:100%;" />
                    </el-form-item>
                    <el-form-item label="处理结果">{{ info.result }}</el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="联动预案" name="4" v-if="scenarios.length > 0 && action.is_scenarios"
                :class="$style['scenarios-wrapper']">
                <el-select v-model="scenarios_id" placeholder="选择联动流程" @change="chooseScenarios">
                    <el-option v-for="(item, index) in scenarios" :key="index" :label="item.name" :value="item.id" />
                </el-select>
                <div :class="$style['view-container']" v-if="scenariosInfo?.type == 'WORD'">
                    <VueOfficeDocx :src="scenariosInfo.url" :class="$style['view-item-wrapper']" />
                </div>
                <div :class="$style['view-container']" v-if="scenariosInfo?.type == 'PDF'">
                    <iframe :src="scenariosInfo.url" :class="$style['view-item-wrapper']"></iframe>
                </div>
                <div :class="$style['image-container']" v-if="scenariosInfo?.type == 'IMAGE'">
                    <el-image :src="scenariosInfo.url" />
                </div>
                <div :class="$style['view-container']" v-if="scenariosInfo?.type == 'XLSX'">
                    <VueOfficeExcel :src="scenariosInfo.url" :class="$style['view-item-wrapper']" />
                </div>
            </el-tab-pane>
        </el-tabs>
        <div :class="$style['event-button-container']">
            <el-button size="small" @click="show = false">取消</el-button>
            <!-- <el-button size="small" type="primary" @click="onSubmit">确认</el-button> -->
            <el-popover placement="top-end" :width="270" trigger="click" :visible="visible" v-if="action.is_forward">
                <template #reference>
                    <el-button size="small" type="danger" @click="visible = !visible">转发至其他用户组</el-button>
                </template>
                <div style="display: flex; align-items: center; justify-content: space-between;">
                    <el-button size="small" type="primary" @click="forwardSubmit()">确认转发</el-button>
                    <el-button size="small" @click="visible = false">取消</el-button>
                </div>
                <el-checkbox-group v-model="checkedRoleIds" :class="$style['checkbox-group-wrapper']">
                    <el-checkbox v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
                        {{ item.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-popover>
        </div>
    </div>

</template>
<script setup>
import { ref, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchEventVote, fetchEventForward } from '@/api/event.services'
import { fetchLinkageScenariosDocument } from '@/api/linkage.services'
import { fetchRoleBasic } from '@/api/role'
import { Close } from '@element-plus/icons-vue'
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'
import '@vue-office/docx/lib/index.css'
const activeName = ref('1')
const info = ref({})
const show = ref(false)
// 添加拖拽相关变量
const dragRef = ref(null)
const position = ref({ x: 0, y: 0 })
const isDragging = ref(false)
const startPos = ref({ x: 0, y: 0 })
let initialPosition
/***
 * * @description: 开始拖拽
 * * @param event
 * */
const startDrag = (event) => {
    if (event.target.closest('.el-icon')) return // 如果点击的是关闭按钮，不启动拖拽

    isDragging.value = true
    startPos.value = {
        x: event.clientX,
        y: event.clientY
    }

    // 记录初始位置
    initialPosition = {
        x: position.value.x,
        y: position.value.y
    }
    // console.log('initialPosition', initialPosition)
    // 添加鼠标移动和松开事件监听
    document.addEventListener('mousemove', onDrag)
    document.addEventListener('mouseup', stopDrag)

    // 阻止默认行为和冒泡
    event.preventDefault()
}
/***
 * * @description: 报警信息框拖拽
 * * @param {MouseEvent} e
 */
const onDrag = (e) => {
    if (!isDragging.value) return
    // 计算移动距离
    const deltaX = e.clientX - startPos.value.x
    const deltaY = e.clientY - startPos.value.y
    // 更新位置
    position.value = {
        x: initialPosition.x + deltaX,
        y: initialPosition.y + deltaY
    }
}
/***
 * * @description: 停止拖拽
 * * @param {MouseEvent} e
 * */
const stopDrag = () => {
    isDragging.value = false
    document.removeEventListener('mousemove', onDrag)
    document.removeEventListener('mouseup', stopDrag)
}
/***
 * * @description: 打开报警信息框
 * * @param {Object} msg
 * * @param {Array} data
 */
const action = ref({
    is_scenarios: false,
    is_forward: false
})
const open = (message) => {
    // console.log('打开预案', message)
    if (info.value && message.event.event_id == info.value.event_id) {
        if (message.action == 8) {
            initRoleBasic()
            action.value.is_forward = true
        }
        if (message.action == 9) {
            initActionScenarios()
            action.value.is_scenarios = true
        }
        return
    }
    action.value = {
        is_scenarios: false,
        is_forward: false
    }
    info.value = message.event
    if (message.action == 8) {
        initRoleBasic()
        action.value.is_forward = true
    }
    if (message.action == 9) {
        initActionScenarios()
        action.value.is_scenarios = true
    }
    show.value = true
    //重置位置
    position.value = { x: 0, y: 0 }
}
defineExpose({
    open
})
/***
 * * @description: 组件卸载时清理事件监听
 */
onUnmounted(() => {
    document.removeEventListener('mousemove', onDrag)
    document.removeEventListener('mouseup', stopDrag)
})

const onSubmit = async () => {
    const result = await fetchEventVote(info.value)
    if (result.code == 1) {
        show.value = false
    }
}
const switchTab = async () => {
    //联动预案
    if (activeName.value == '4') {
        initActionScenarios()
    }
}
const visible = ref(false)
const checkedRoleIds = ref([])
const roleList = ref([])
const initRoleBasic = async () => {
    const result = await fetchRoleBasic()
    if (result.code == 1) {
        roleList.value = result.data
    }
}
const forwardSubmit = async () => {
    if (checkedRoleIds.value.length == 0) {
        ElMessage.warning('请选择角色')
        return
    }
    const params = {
        event: info.value,
        ids: checkedRoleIds.value,
        is_scenarios: action.value.is_scenarios
    }
    const result = await fetchEventForward(params)
    if (result.code == 1) {
        ElMessage.success('转发成功')
        visible.value = false
        show.value = false
    }
}
const scenarios = ref([])
const scenariosInfo = ref({})
const scenarios_id = ref(null)
const initActionScenarios = async () => {
    const params = {
        device_id: info.value.device_id,
        cid: info.value.cid
    }
    const result = await fetchLinkageScenariosDocument(params)
    if (result.code == 1) {
        scenarios.value = result.data || []
        scenariosInfo.value = result.data[0] || {}
        scenarios_id.value = result.data[0]?.id || null
    }
}
// initActionScenarios()
const chooseScenarios = (id) => {
    scenariosInfo.value = scenarios.value.find(item => item.id == id)
}
</script>
<style lang="scss" module>
.event-container-fixed {
    position: fixed;
    width: 700px;
    height: 550px;
    background: #FFFFFF;
    /* 上下左右居中的样式 */
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 999;
    box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.22);
    border-radius: 4px;
    border: 1px solid #D5D8E2;
    background-image: url('@/assets/event-fixed-bg.png');
    background-size: 100%;
    background-repeat: no-repeat;
    display: flex;
    flex-direction: column;
}

.event-tooltip {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    height: 35px;
    padding: 0 10px;
    align-items: center;

    & [class~='el-icon'] {
        cursor: pointer;
    }
}

.event-icon-wrapper {
    font-size: 14px;
    font-weight: bold;
    color: #EF1824;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;

    & [class~='el-image'] {
        width: 20px;
        height: 20px;
        margin-right: 5px;
    }
}

.event-content-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0 10px;
    box-sizing: border-box;
    overflow: hidden;

    & [class~='el-tabs__header'] {
        margin: 0;
        height: 35px;
    }

    & [class~='el-tabs__content'] {
        flex: 1;
        padding: 10px 0;
        display: flex;
        overflow-y: auto;
        @include scrollbar;

        & [class~='el-tab-pane'] {
            flex: 1;
            padding: 0;
            display: flex;
        }

        & [class~='el-form'] {
            width: 100%;
        }

        & [class~='el-form-item'] {
            margin-bottom: 5px;
        }
    }
}

.event-button-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    border-radius: 0px 0px 4px 4px;
    border: 1px solid #D5D8E2;

    & [class~='el-button'] {
        width: 80px;
    }

    & [class~='el-button']:not(:last-child) {
        margin-right: 20px;
    }

    & [class~='el-button']:last-child {
        width: 120px;
    }
}

.checkbox-group-wrapper {
    padding: 5px;
    display: flex;
    flex-direction: column;
}

.scenarios-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.view-container {
    flex: 1;
    padding: 10px 0;
    display: flex;
    overflow: hidden;
}

.view-item-wrapper {
    flex: 1;
    background: #ccc;
}
</style>